/**
 *@brief  MatterBridge 管理Mesh与Matter节点之间的关系
 */
#pragma once

#include <json/json.h>

#include "BridgedDevice.h"
#include "WebsocketClient.h"

class MatterBridge: BridgedDeviceDelegate, WebSocketClient::Delegate
{
public:
    ChipError LoadConfig(const std::string& filename);
    ~MatterBridge() override;

    [[nodiscard]] BridgedDevice* GetDeviceByIndex(int index) const;
    [[nodiscard]] BridgedDevice* GetDeviceByEndpoint(EndpointId endpointId) const;
    int AttachNodes();

    // - BridgedDeviceDelegate
    void OnMessageSend(DataBlock* block) override;
    void OnStatusChanged(app::ConcreteAttributePath* path) override;
    void OnGetRemoteAttribute(Path *path) override;

    // - MeshGwDelegate
    void OnWebSocketMessageReceived(const Json::Value& root) override;
    void OnWebSocketStateChanged(WebSocketClient::State state) override;

private:
    int LoadNodes(const Json::Value& initParams);
    int AttachDevice(BridgedDevice *dev);
    int DetachDevice(BridgedDevice *dev);

    // 单例模式
    MatterBridge();
    static MatterBridge sInstance;
    friend MatterBridge& BridgedMgr();

    EndpointId mBridgeAnonymousEndpointId = 1;

    WebSocketClient* mClient = nullptr;
    std::vector<const BasicInformation*> mNodes{};

    BridgedDevice *mDevices[CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT] = {};
    [[nodiscard]] uint16_t GetNullptrIndex() const;
};

inline MatterBridge& BridgedMgr() {
    return MatterBridge::sInstance;
}